package net.lainiao.manager.control;

import com.github.pagehelper.PageInfo;
import net.lainiao.base.model.Account;
import net.lainiao.service.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Created by Administrator on 2017/1/5.
 */
@Controller
@RequestMapping("/account")
public class AccountControl {
    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(ModelMap modelMap){
        return index(modelMap,1);
    }

    @RequestMapping(value = "/index/{pageIndex}", method = RequestMethod.GET)
    public String index(ModelMap modelMap,@PathVariable Integer pageIndex) {
        PageInfo<Account> pageInfo = accountService.getAllForPage(pageIndex, 10);
        modelMap.put("data", pageInfo.getList());
        int pageTotal=pageInfo.getPages();
        modelMap.put("pageTotal",pageTotal);
        int pageStart=pageIndex-5;
        int pageEnd=pageIndex+5;
        if(pageStart<1){
            pageStart=1;
        }
        if(pageEnd>pageTotal){
            pageEnd=pageTotal;
        }
        modelMap.put("pageStart",pageStart);
        modelMap.put("pageEnd",pageEnd);
        modelMap.put("pageIndex",pageIndex);
        return "account/index";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap modelMap) {
        return "account/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(ModelMap modelMap, @ModelAttribute Account account) {
        int count = accountService.save(account);
        if (count > 0) {
            return "redirect:/account/index";
        }
        modelMap.put("Mess", "新增失败");
        return "account/add";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(ModelMap modelMap,@PathVariable  String id) {
        Account account=accountService.getById(id);
        modelMap.put("net.lainiao.zhihu.model",account);
        return "account/edit";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(ModelMap modelMap, @ModelAttribute Account account) {
        int count = accountService.save(account);
        if (count > 0) {
            return "redirect:/account/index";
        }
        modelMap.put("Mess", "保存失败");
        return "account/add";
    }

    @RequestMapping(value="/del/{id}",method = RequestMethod.GET)
    public String del(@PathVariable  String id,ModelMap modelMap){
         accountService.del(id);
         return "redirect:/account/index";
    }
}
